package cn.jbolt.core.enjoy.directive;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.jbolt.core.consts.JBoltConst;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

import java.io.IOException;

/**
 * 服务器物理绝对路径地址图片转base64
 *
 * @ClassName: ImagePathToBase64Directive
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2021年2月15日17:43:51
 */
public class ImagePathToBase64Directive extends Directive {
	private Expr pathExpr;
	private int paraNum;

	@Override
	public void setExprList(ExprList exprList) {
		this.paraNum = exprList.length();
		if (paraNum == 1) {
			this.pathExpr = exprList.getExpr(0);
		}else{
			throw new ParseException(
					"Wrong number parameter of #imgPathToBase64 directive", location);
		}
	}

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		if (paraNum == 0) {
			outputNothing(env, writer);
		} else {
			outputBase64(env, scope, writer);
		}
	}

	private void outputBase64(Env env, Scope scope, Writer writer) {
		if (this.pathExpr == null) {
			outputNothing(env, writer);
			return;
		}

		Object pathObj = this.pathExpr.eval(scope);
		if (pathObj == null) {
			outputNothing(env, writer);
			return;
		}

		String path = pathObj.toString();
		if (StrUtil.isBlank(path)) {
			outputNothing(env, writer);
			return;
		}

		if (!FileUtil.isAbsolutePath(path)) {
			throw new ParseException(
					"Wrong imgPath of #imgPathToBase64 directive, must absolutePath", location);
		}

		String base64 = Base64.encode(FileUtil.file(path));
		if (base64 == null) {
			outputNothing(env, writer);
			return;
		}

		try {
			writer.write(base64);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 输出空字符
	 *
	 * @param env
	 * @param writer
	 */
	private void outputNothing(Env env, Writer writer) {
		try {
			writer.write(JBoltConst.IMG_NOTHING_BASE64_FILE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}



}
